package com.newStart.proxyDemo.dynamicProxy;

import com.newStart.proxyDemo.staticProxy.Buyer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Project: tobe-better-coder
 * Package: com.newStart.proxyDemo.dynamicProxy
 *
 * @author : Mr.xu
 * @date : 2022/8/15 23:50
 */
public class TestMain {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//        Method method = SayHello.class.getMethod("sayHello",String.class);
//        SayHello sayHelloChinese = new SayHelloChineseImpl();
//        SayHello sayHelloEnglish = new SayHelloEnglishImpl();
//        method.invoke(sayHelloChinese,"张三");
//        method.invoke(sayHelloEnglish,"李四");
        testProxy("张三");
        SayHelloChineseImpl sayHelloChinese = new SayHelloChineseImpl();
        SayHello sayHello1 = (SayHello) Proxy.newProxyInstance(sayHelloChinese.getClass().getClassLoader(), sayHelloChinese.getClass().getInterfaces(), new Proxyer(sayHelloChinese));
        sayHello1.sayHello("李四");
        sayHello1.sayHi("李四");
        SayHelloEnglishImpl sayHelloEnglish = new SayHelloEnglishImpl();
        SayHello sayHelloE = (SayHello) Proxy.newProxyInstance(sayHelloChinese.getClass().getClassLoader(), sayHelloEnglish.getClass().getInterfaces(), new Proxyer(sayHelloEnglish));
        sayHelloE.sayHello("李四");
        sayHelloE.sayHi("李四");
        SayHello sayHello2 = (SayHello) Proxy.newProxyInstance(Buyer.class.getClassLoader(), new Class<?>[]{SayHello.class}, new ProxyerNoImpl());
        sayHello2.sayHello("王五");
        sayHello2.sayHi("王五");
    }

    public static void testProxy(String name) {
        SayHelloChineseImpl sayHelloChinese = new SayHelloChineseImpl();
        SayHello sayHello = (SayHello) Proxy.newProxyInstance(TestMain.class.getClassLoader(), new Class<?>[]{SayHello.class}, new ProxyerNoImpl() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return method.invoke(sayHelloChinese, args);
            }
        });
        sayHello.sayHello(name);
    }
}